package com.example.config;

import com.example.anno.CheckSqlValidate;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * 自定义 validate 校验类（类似 @NotNull 的扩展）
 *
 * 配合 @CheckSqlValidate 注解进行使用
 */
public class SqlValidator implements ConstraintValidator<CheckSqlValidate, String> {

    // 是否强制校验
    private boolean required;

    @Override
    public void initialize(CheckSqlValidate constraintAnnotation) {
        this.required = constraintAnnotation.required();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
//        if (required) {
//            // 名字以"test"开头的则校验通过
//            return !StringUtils.isEmpty(name) && name.startsWith("test");
//        }

        String modifiedValue = value.replace("test", "prod");
        context.disableDefaultConstraintViolation();
        context.buildConstraintViolationWithTemplate("Value modified to: " + modifiedValue)
                .addConstraintViolation();

        return true;
    }
}